import md5 from 'js-md5'
import api from './api.js'

// 分片上传
/*
 * 分片上传函数 支持多个文件
 * @param options
 * options.file 表示源文件
 * options.pieceSize 表示需要分片的大小 默认是5m
 * options.chunkUrl 分片上传的后端地址
 * options.fileUrl 整个文件的上传地址
 * progress 进度回调
 * success 成功回调
 * error 失败回调
 *
 */
export const uploadByPieces = ({
	files,
	pieceSize = 5,
	progress,
	success,
	error
}) => {

	if (!files || !files.length){
		return
	} 
	// 上传过程中用到的变量
	let fileList = []; // 总文件列表
	let progressNum = 1; // 进度
	let successAllCount = 0; // 上传成功的片数
	let currentAllChunk = 0; // 当前上传的片数索引
	let AllChunk = 0 ;// 所有文件的chunk数之和
	let AllFileSize = 0; // 所有文件size
	// 获取md5
	const readFileMD5 = (files) => {
		// 读取每个文件的md5
		files.map((file, index) => {
			let fileRederInstance = new FileReader()
			fileRederInstance.readAsBinaryString(file)
			fileRederInstance.addEventListener('load', e => {
				let fileBolb = e.target.result
				let fileMD5 = md5(fileBolb)
				if (!fileList.some((arr) => arr.md5 === fileMD5)) {
					fileList.push({
						fileMD5: fileMD5,
						name: file.name,
						file
					})
					AllFileSize = AllFileSize + file.size
				}
				if (index === files.length - 1) readChunkMD5(fileList)
			}, false)
		})
	}
	const getChunkInfo = (file, currentChunk, chunkSize) => {
		let start = currentChunk * chunkSize
		let end = Math.min(file.size, start + chunkSize)
		let chunk = file.slice(start, end)
		return {
			start,
			end,
			chunk
		}
	}
	// 针对每个文件进行chunk处理
	const readChunkMD5 = async (fileList) => {
		for (let fileIndex = 0; fileIndex < fileList.length; fileList++) {
			let currentFile = fileList[fileIndex];
			const chunkSize = pieceSize * 1024 * 1024 // 20MB一片
			const chunkCount = Math.ceil(currentFile.file.size / chunkSize) // 总片数
			AllChunk = AllChunk + chunkCount // 计算全局chunk数
			// let fileSize = currentFile.file.size // 文件大小
			// 针对单个文件进行chunk上传
			for (let i = 0; i < chunkCount;) {
				const {	chunk} = getChunkInfo(currentFile.file, i, chunkSize);
				console.log("正在上传第"+i)
				// let chunkFR = new FileReader();
				// chunkFR.readAsBinaryString(chunk);
				// chunkFR.onload = async function(e) {
				// 	let chunkBolb = e.target.result
				// 	let chunkMD5 = md5(chunkBolb)
				// 	let res = await  uploadChunk(currentFile, {
				// 		chunkMD5,
				// 		chunk,
				// 		currentChunk: i,
				// 		chunkCount
				// 	}, fileIndex);
				// 	// resolve(res)
				// 	console.log(res)
				// }
				await test(currentFile,chunk,chunkCount,fileIndex,i).then(res=>{
					console.log(res)
					 i = res
				})
				// chunkFR.addEventListener('load', e => {

				// }, false)
			}
		}
		// fileList.map((currentFile, fileIndex) => {

		// })
	}
	const test = (currentFile,chunk,chunkCount,fileIndex,chunkIndex)=>{
		return new Promise( (resolve,reject)=>{
			let chunkFR = new FileReader();
			chunkFR.readAsBinaryString(chunk);
			chunkFR.onload = async function(e) {
				let chunkBolb = e.target.result
				let chunkMD5 = md5(chunkBolb)
				let res = await  uploadChunk(currentFile, {
					chunkMD5,
					chunk,
					currentChunk: chunkIndex,
					chunkCount
				}, fileIndex);
				resolve(res)
				console.log(res)
			}
		})
	}
	// 更新进度
	const progressFun = () => {
		progressNum = Math.ceil(successAllCount / AllChunk * 100)
		progress(progressNum)
	}
	// 对分片已经处理完毕的文件进行上传
	const uploadFile = (currentFile) => {
		let makeFileForm = new FormData()
		makeFileForm.append('md5', currentFile.fileMD5)
		makeFileForm.append('file_name', currentFile.name)
		console.log("进入了整文件上传")
		// fetch({ // 合并文件
		//   type: 'post',
		//   url: fileUrl,
		//   data: makeFileForm
		// }).then(res => {
		//   progressFun()
		//   res.file_name = currentFile.name
		//   success && success(res)
		//   successAllCount++
		// }).catch(e => {
		//   error && error(e)
		// })
	}
	const  uploadChunk =  async (currentFile, chunkInfo, fileIndex) => {
		let fetchForm = new FormData()
		fetchForm.append('fileSizeTotal', currentFile.file.size)
		fetchForm.append('fileName', currentFile.name)
		fetchForm.append('fileMD5', currentFile.fileMD5)
		fetchForm.append('file', chunkInfo.chunk)
		fetchForm.append('slicesNum', chunkInfo.chunkCount)
		fetchForm.append('slicesId', chunkInfo.currentChunk)
		
		// fetchForm.append('fileMD5', chunkInfo.chunkMD5)
		return await api.uploadTeachVideo(fetchForm).then(res => {
			successAllCount++
			progressFun()
			let currentChunk = 0;
			if(Number(res.errCode) == 0 && res.data){
				let slicesIds = res.data.slicesIds;//已上传的索引
				let ids = slicesIds.split(",");
				currentChunk = Number(ids[ids.length - 1]);
			}
			return currentChunk+1 ;
		}).catch((e) => {
			error && error(e)
			return chunkInfo.currentChunk;
		})
	}
	readFileMD5(files) // 开始执行代码
}
